package com.demo.personalaccountingbackend.utils;

import com.demo.personalaccountingbackend.data.MyUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 类描述信息
 *
 * @author zgx
 * @version 1.0
 * @date 2025/10/23 15:46
 */

@Component
public class SecurityUtils {

    /**
     * 获取当前登录用户ID - 最简单实现
     */
    public static Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("当前认证对象: " + authentication);
        System.out.println("是否认证: " + (authentication != null && authentication.isAuthenticated()));
        if (authentication != null && authentication.getPrincipal() instanceof MyUserDetails) {
            Object principal = authentication.getPrincipal();
            System.out.println("Principal类型: " + (principal != null ? principal.getClass() : "null"));
            if (principal instanceof UserDetails) {
                MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
                return userDetails.getId();
            }

        }
        throw new RuntimeException("用户未登录或登录信息无效");
    }
}